using System;
using System.Collections.Generic;
using System.Text;

namespace Deepcode.Flux.Core.Services.FileSystem
{
	/// <summary>
	/// Path check service allows for the interrogation and creation of file system paths.
	/// </summary>
	public class PathCheckService
	{
		#region Internal utility
		/// <summary>
		/// Takes the path passed in and returns the real physical path.
		/// If the path starts with ~/ the path is resolved relative to the
		/// IIS virtual directory, otherwise the path is deemed to be a physical path
		/// anyway. Used internally only.
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
		protected string GetRealPath(string path)
		{
			if (path.StartsWith("~/"))
			{
				return Reformat(System.Web.HttpContext.Current.Server.MapPath( path ));
			}
			else return Reformat(path);
		}
		/// <summary>
		/// Takes the physical path specified and ensures all path seperators are the 
		/// right way around and that the path does not end with a seperator
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
		protected string Reformat(string path)
		{
			string result = path.Replace("/", "\\");
			if( result.EndsWith("\\")) result = result.Substring(0, result.Length-1);
			return result;
		}
		#endregion
		/// <summary>
		/// Determines if a path exists, optionally creating it on the fly
		/// </summary>
		/// <param name="path"></param>
		/// <param name="bCreate"></param>
		/// <returns></returns>
		public bool PathExists(string path, bool bCreate)
		{
			string FullPath = GetRealPath(path);
			string[] Paths = FullPath.Split('\\');

			string concat = "";
			foreach (string p in Paths)
			{
				if (concat != "") concat += "\\";
				concat += p;
				
				if (!System.IO.Directory.Exists(concat))
				{
					if (bCreate)
					{
						try { System.IO.Directory.CreateDirectory(concat); }
						catch { return false; }
					}
					else return false;
				}
			}
			return true;
		}

		/// <summary>
		/// Determines if the path specified exists
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
		public bool PathExists(string path)
		{
			return PathExists( path, false );
		}
		/// <summary>
		/// Determines if the path specified exists, and if not
		/// creates it as necessary.
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
		public bool PathCreate(string path)
		{
			return PathExists( path, true );
		}
	}
}
